package com.wugh.fast.security.social.view;

import com.alibaba.fastjson.JSON;
import com.wugh.fast.module.api.vo.ResponseVO;
import com.wugh.fast.security.social.vo.UserConnectionVO;
import org.springframework.social.connect.Connection;
import org.springframework.web.servlet.view.AbstractView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 说明: 链接状态视图
 *
 * @author wugh
 * @date 2018/9/18 10:32
 */
public class ConnectStatusView extends AbstractView {

    @Override
    protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
                                           HttpServletResponse response) throws Exception {

        Map<String, List<Connection<?>>> connections = (Map<String, List<Connection<?>>>) model.get("connectionMap");
        List<UserConnectionVO> connectionVOs = connections.keySet().stream().filter(providerId->connections.get(providerId).size()>0).map(providerId -> {
            UserConnectionVO userConnectionVO = new UserConnectionVO();
            userConnectionVO.setProviderId(providerId);
            Connection<?> connection = connections.get(providerId).stream().findFirst().get();
            userConnectionVO.setDisplayName(connection.getDisplayName());
            userConnectionVO.setImageurl(connection.getImageUrl());
            return userConnectionVO;
        }).collect(Collectors.toList());

        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(ResponseVO.ok(connectionVOs)));
    }

}
